package simulation;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import lookandfeel.colorScheme;
import lookandfeel.customButton;

import gui.BackgroundPanel;

public class Startup extends JFrame
{
	private static final long serialVersionUID = 1L;
	
	private customButton btn_OK = new customButton("Connect");
	private customButton btn_Cancel = new customButton("Cancel");
	private JTextField txt_Username = new JTextField("username");
	private JTextField txt_IP = new JTextField("localhost");
	private JTextField txt_Port = new JTextField("28000");
	private JPanel container = new BackgroundPanel("./images/startup_bg.png");
	private String username = "";
	
		
	public static void main(String[] args) throws Exception 
	{
		new colorScheme();
		new Startup();
	}
	
	// Open frame to insert Server IP:Port
	private Startup()
	{
		// Initialize
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setTitle(Config.appTitle);
		this.getContentPane().add(container);
		this.setPreferredSize(new Dimension(300, 150));
		this.setUndecorated(true);
		this.setVisible(true);
		this.setAlwaysOnTop(true);
		this.setResizable(false);
		
		// Get the size of the screen
	    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
	    
	    // Determine the new location of the window
	    int w = this.getPreferredSize().width;
	    int h = this.getPreferredSize().height;
	    int x = (dim.width-w)/2;
	    int y = (dim.height-h)/2;
	    
	    // Move the window
	    this.setLocation(x, y);
		btn_OK.requestFocusInWindow();
		btn_OK.setEnabled(false);

		final JFrame _self = this;
		
		// Set Connect button
		this.btn_OK.addActionListener(new ActionListener() 
		{
            public void actionPerformed(ActionEvent paramActionEvent) 
            {
            	try 
            	{
            		username = txt_Username.getText();
            		Config.cajoHost = txt_IP.getText();
            		Config.cajoPort = Integer.parseInt(txt_Port.getText());
            		
            		if((Config.cajoHost != null) && (String.valueOf(Config.cajoPort) != null))
					{
            			try
            			{
            				System.out.println("Connecting to: " + Config.cajoHost + ":" + Config.cajoPort);
            				System.out.println("Username:" + username);
            				
            				//Go to Connection.java to establish an connection
            				if(Connection.init())
            				{
            					System.out.println("Connection successful!");
            					// Log user in
        						Connection.login(username);
        						
        						// Open next frame (teamSelection)
        						new teamSelection(_self);
            				}
            			}
            			catch (Exception e) {
							System.out.println("ERROR: Could not connect to " + Config.cajoHost + ":" + Config.cajoPort);
						}
					}
				} 
            	catch (Exception e) 
            	{
					System.out.println("ERROR: Can't set variables to configuration.");
				}
            }
		});
		
        // Set Cancel button
		this.btn_Cancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent paramActionEvent) {
            	try {
					System.exit(1);
				} catch (Exception e) {
					System.out.println("ERROR: Client application could not shut down. Please try again...");
				}
            }
        });
		
		// Set textUsername
		this.txt_Username.addKeyListener(new KeyListener() {

			public void keyTyped(KeyEvent e) {}
			public void keyReleased(KeyEvent e) {

				if(txt_Username.getText().length() > 0){
					btn_OK.setEnabled(true);
				}
				else{
					btn_OK.setEnabled(false);
				}
			}
			public void keyPressed(KeyEvent e) {}

		});
		this.txt_Username.addFocusListener(new FocusListener() {
			String sampleText = "username";
			@Override
			public void focusLost(FocusEvent arg0) {
				String currentValue = txt_Username.getText();
				currentValue = currentValue.replaceAll(" ", "");
				if(currentValue.equalsIgnoreCase("")){
					txt_Username.setText(sampleText);
				}

			}

			@Override
			public void focusGained(FocusEvent arg0) {
				if(txt_Username.getText().equalsIgnoreCase(sampleText)){
					txt_Username.setText("");
				}
			}
		});
		
		// Set textIPBox
		this.txt_IP.addFocusListener(new FocusListener() {
			String sampleText = "localhost";
			@Override
			public void focusLost(FocusEvent arg0) {
				String currentValue = txt_IP.getText();
				currentValue = currentValue.replaceAll(" ", "");
				if(currentValue.equalsIgnoreCase("")){
					txt_IP.setText(sampleText);
				}
			}

			@Override
			public void focusGained(FocusEvent arg0) {
				if(txt_IP.getText().equalsIgnoreCase(sampleText)){
					txt_IP.setText("");
				}
			}
		});
		
		// Set textPortBox
		this.txt_Port.addFocusListener(new FocusListener() {
			String sampleText = "28000";
			@Override
			public void focusLost(FocusEvent arg0) {
				String currentValue = txt_Port.getText();
				currentValue = currentValue.replaceAll(" ", "");
				if(currentValue.equalsIgnoreCase("")){
					txt_Port.setText(sampleText);
				}
			}

			@Override
			public void focusGained(FocusEvent arg0) {
				if(txt_Port.getText().equalsIgnoreCase(sampleText)){
					txt_Port.setText("");
				}
				
			}
		});
		
		txt_IP.setBorder(BorderFactory.createLineBorder(new Color(28,28,28), 1));
		txt_Port.setBorder(BorderFactory.createLineBorder(new Color(28,28,28), 1));
		
		txt_Username.setPreferredSize(new Dimension(100,20));
		txt_IP.setPreferredSize(new Dimension(100,20));
		txt_Port.setPreferredSize(new Dimension(40, 20));
		
		// Add to frame
		JPanel pnlUsername = new JPanel();
			pnlUsername.setOpaque(false);
			pnlUsername.setBorder(BorderFactory.createEmptyBorder(20, 0, 0, 47));
			pnlUsername.add(new JLabel("Username"));
			txt_Username.setBorder(BorderFactory.createLineBorder(new Color(28,28,28), 1));
			pnlUsername.add(txt_Username);
		JPanel pnlLabels = new JPanel();
		pnlLabels.setOpaque(false);
			pnlLabels.add(new JLabel("Server address"));
				pnlLabels.add(txt_IP);
			pnlLabels.add(new JLabel("Port"));
				pnlLabels.add(txt_Port);
		JPanel pnlButtons = new JPanel();
		pnlButtons.setOpaque(false);
			pnlButtons.add(btn_Cancel);
			pnlButtons.add(btn_OK);
		
			// Check if text fields are empty
			if((txt_Username.getText() == "username") || (txt_IP.getText() == "") || (txt_Port.getText() == ""))
				btn_OK.setEnabled(false);
		
		// Add all panels to container
		container.add(pnlUsername);
		container.add(pnlLabels);
		container.add(pnlButtons);
		
		this.pack();
	}
}